import React, { useState, useEffect, useRef, useCallback } from "react";
import GamepadController from "../utils/GamepadController";

import { MODE_VIRTUAL_POINTER } from "../utils/constants.js";

// 常量定义
const MOUSE_SPEED = 7;
const BUTTON_A = 0;
const POINTER_SIZE = 20;
const AXIS_THRESHOLD = 0.1;
const MOVE_INTERVAL = 20;

const Pointer = (props) => {
  const [position, setPosition] = useState({ 
    x: window.innerWidth / 2, 
    y: window.innerHeight / 2 
  });
  const [screenSize, setScreenSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });
  const pointerRef = useRef(null);
  const controller = GamepadController.getInstance();
  const timer = useRef(null);
  const positionRef = useRef(position);
  const screenSizeRef = useRef(screenSize);

  useEffect(() => {
    // 获取初始鼠标位置（屏幕中心）
    // 注册游戏手柄事件监听器
    controller.registerModeEventHandler(
      MODE_VIRTUAL_POINTER,
      handleGamepadEvent
    );

    return () => {
      // 清理事件监听器
      timer.current && clearInterval(timer.current);
    }
  }, []);

  // 更新指针位置
  useEffect(() => {
    if (pointerRef.current) {
      pointerRef.current.style.left = `${position.x}px`;
      pointerRef.current.style.top = `${position.y}px`;
    }
    positionRef.current = position;
  }, [position]);

  useEffect(() => { 
    screenSizeRef.current = screenSize;
  }, [screenSize]);

  // 监听父容器尺寸变化并调整指针位置
  useEffect(() => {
    const pointerElement = pointerRef.current;
    if (!pointerElement) return;
    
    const parentContainer = pointerElement.parentElement;
    if (!parentContainer) return;
    
    const handleResize = () => {
      const newWidth = parentContainer.clientWidth;
      const newHeight = parentContainer.clientHeight;
      setScreenSize({ width: newWidth, height: newHeight });
      // 将指针位置调整到父容器中心
      setPosition({ 
        x: newWidth / 2,
        y: newHeight / 2 
      });
    };
    
    // 初始设置
    handleResize();
    
    // 使用ResizeObserver监听父容器尺寸变化
    const observer = new ResizeObserver(entries => {
      handleResize();
    });
    
    observer.observe(parentContainer);
    
    return () => {
      observer.disconnect();
    };
  }, []);

  /**
   * 根据摇杆输入更新指针位置
   * @param {Object} axes - 摇杆输入值 {x, y}
   */
  const movePointer = useCallback((axes) => {
    // 限制坐标为小数点后三位
    const round = (num) => Math.round(num * 1000) / 1000;
    console.log('screenSize', screenSize)
    setPosition((prev) => ({
      x: Math.max(
        0,
        Math.min(
          round(prev.x + axes.x * MOUSE_SPEED),
          screenSizeRef.current.width - POINTER_SIZE / 2
        )
      ),
      y: Math.max(
        0,
        Math.min(
          round(prev.y + axes.y * MOUSE_SPEED),
          screenSizeRef.current.height - POINTER_SIZE / 2
        )
      ),
    }));
  }, [position]);
  // 监听游戏手柄事件
  /**
   * 处理游戏手柄移动事件
   * @param {Object} axes - 摇杆坐标
   */
  const handleMoveEvent = useCallback((axes) => {
    const { x: xAxis, y: yAxis } = axes;
    timer.current && clearInterval(timer.current);
    
    if (Math.abs(xAxis) < AXIS_THRESHOLD && Math.abs(yAxis) < AXIS_THRESHOLD) {
      return;
    }
    
    movePointer({ x: xAxis, y: yAxis });
    timer.current = setInterval(
      () => movePointer({ x: xAxis, y: yAxis }),
      MOVE_INTERVAL
    );
  }, [movePointer]);

  /**
   * 处理游戏手柄按钮按下事件
   */
  const handleButtonPress = () => {
    const evt = createTouchEvent()
    props.triggerTouchEvent('down', evt );
  }

  /**
   * 处理游戏手柄按钮释放事件
   */
  const handleButtonRelease = () => {
    props.triggerTouchEvent('up', createTouchEvent());
  }

  /**
   * 监听游戏手柄事件入口
   */
  const handleGamepadEvent = useCallback((e) => {
    if (e.eventType === "move" && e.detail && e.detail.axes) {
      const [xAxis, yAxis] = e.detail.axes;
// console.log("handleGamepadEvent", xAxis, yAxis);
      handleMoveEvent({ x: xAxis, y: yAxis });
    } else if (e.eventType === "press" && e.detail.index === BUTTON_A) {
      handleButtonPress();
    } else if (e.eventType === "release" && e.detail.index === BUTTON_A) {
      handleButtonRelease();
    }
  }, [handleMoveEvent, handleButtonPress, handleButtonRelease]);

  /**
   * 创建触摸事件对象
   * @returns {Object} 触摸事件对象
   */
  const createTouchEvent = () => {
    console.log('createTouchEvent position:', position, positionRef.current);
    // 根据游戏手柄动作创建触摸事件对象
    return {
      nativeEvent: {
        changedTouches: [{
          clientX: positionRef.current.x,
          clientY: positionRef.current.y,
          identifier: 1
        }]
      }
    }
  }


  return (
    <div
      ref={pointerRef}
      style={{
      position: "absolute",
      width: `${POINTER_SIZE}px`,
      height: `${POINTER_SIZE}px`,
      pointerEvents: "none",
      zIndex: 9999,
      transition: "transform 0.1s ease-out"
    }}
    >
      <svg
        className="w-6 h-6"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="3049"
        width="200"
        height="200"
      >
        <path
          d="M57.782857 29.988571c7.314286-1.462857 13.897143-0.731429 20.48 2.194286L967.68 387.657143c7.314286 2.925714 13.897143 8.045714 17.554286 15.36 4.388571 6.582857 5.851429 14.628571 5.12 23.405714a37.302857 37.302857 0 0 1-10.971429 21.211429 30.72 30.72 0 0 1-20.48 10.24L512 517.851429l-56.32 439.588571a29.988571 29.988571 0 0 1-9.508571 20.48c-5.851429 5.851429-13.165714 9.508571-21.211429 10.971429a37.010286 37.010286 0 0 1-23.405714-5.12 32.841143 32.841143 0 0 1-15.36-17.554286L31.451429 78.994286A33.206857 33.206857 0 0 1 29.257143 58.514286 38.180571 38.180571 0 0 1 57.782857 29.988571z m343.04 777.508572L130.925714 131.657143l680.228572 272.091428-364.982857 49.005715-45.348572 354.742857z"
          fill="#1296db"
          strokeWidth={20}
          stroke="#fff"
          p-id="3050"
        ></path>
      </svg>
    </div>
  );
};

export default Pointer;
